package com.example.word.util;

import android.os.AsyncTask;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * http请求工具
 */
public class HttpUtils {

    /**
     * 服务器地址
     */
    private static final String serverUrl = "https://3a84dd7a.r3.cpolar.cn";
    /**
     * 项目名
     */
    private static final String projectName = "/word_server";

    private static final String testUrl = "http://192.168.3.27:8888";

    public static void test() {

//        Map<String, String> requestParam = new HashMap<>();
//        requestParam.put("requestParam", "requestParam");
//        HttpUtils.sendGetRequest("/requestParam", requestParam, Object.class, new HttpUtils.ApiCallback<Object>() {
//            @Override
//            public void onSuccess(Response response) {
//                // 处理请求成功的情况
//                MessageUtils.show("处理成功！", activity);
//            }
//
//            @Override
//            public void onFailure(Response response) {
//                // 处理请求失败的情况
//                MessageUtils.show(response.getMsg(), activity);
//            }
//        });

    }
    // 定义接口用于异步回调
    public interface ApiCallback<T> {
        void onSuccess(com.example.word.util.Response<T> response);
        void onFailure(com.example.word.util.Response<T> response);
    }

    // 定义接口用于异步回调
    public interface ApiStringCallback {
        void onSuccess(String responseString);
    }

    public static <T>void sendGetRequest(String uri, Map<String, String> params, Class<T> clazz, ApiCallback<T> callback) {
        AsyncTask<Object, Void, com.example.word.util.Response<T>> asyncTask = new AsyncTask<Object, Void, com.example.word.util.Response<T>>() {

            @Override
            protected com.example.word.util.Response<T> doInBackground(Object... objects) {
                com.example.word.util.Response<T> responseObject = new com.example.word.util.Response<>();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                // 设置连接超时时间，单位为秒
                builder.connectTimeout(6, java.util.concurrent.TimeUnit.SECONDS);
                // 设置读取超时时间，单位为秒
                builder.readTimeout(15, java.util.concurrent.TimeUnit.SECONDS);
                // 设置写入超时时间，单位为秒
                builder.writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS);
                OkHttpClient client = builder.build();

                // 构建请求URL，并添加查询参数
                HttpUrl.Builder urlBuilder = HttpUrl.parse(testUrl + projectName + uri).newBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
                }
                String url = urlBuilder.build().toString();

                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    String responseBody = response.body().string();

                    if (response.isSuccessful()) {
                        if (responseBody == null || "".equals(responseBody)) {
                            responseObject.setCode(500);
                            responseObject.setMsg("服务器无响应");
                        } else {
                            Gson gson = new GsonBuilder().setLenient().setPrettyPrinting().create();
                            Map<String, Object> json = gson.fromJson(responseBody, HashMap.class);
                            responseObject.setCode(Integer.parseInt(json.get("code").toString()));
                            responseObject.setMsg((String)json.get("msg"));
                            responseObject.setData(gson.fromJson(gson.toJson(json.get("data")),clazz));
                            //responseObject = gson.fromJson(responseBody, com.example.fruit.util.Response.class);
                        }
                    } else {
                        responseObject.setCode(response.code());
                        responseObject.setMsg( "服务器请求失败 " + response.code() + " " + response.body().string());
                    }
                } catch (Exception e) {
                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                    responseObject.setCode(-1);
                    responseObject.setMsg("连接服务器错误 " + e.getMessage());
                }

                return responseObject;
            }

            @Override
            protected void onPostExecute(com.example.word.util.Response<T> response) {
                if (response.getCode() == 200) {
                    callback.onSuccess(response);
                } else {
                    callback.onFailure(response);
                }
            }
        };

        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public static void sendGetRequestStringResponse(String url, Map<String, String> params, ApiStringCallback callback) {
        AsyncTask<Object, Void, String> asyncTask = new AsyncTask<Object, Void, String>() {

            @Override
            protected String doInBackground(Object... objects) {
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                // 设置连接超时时间，单位为秒
                builder.connectTimeout(6, java.util.concurrent.TimeUnit.SECONDS);
                // 设置读取超时时间，单位为秒
                builder.readTimeout(15, java.util.concurrent.TimeUnit.SECONDS);
                // 设置写入超时时间，单位为秒
                builder.writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS);
                OkHttpClient client = builder.build();

                // 构建请求URL，并添加查询参数
                HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
                }
                String url = urlBuilder.build().toString();

                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try {
                    System.err.println(url+params);
                    Response response = client.newCall(request).execute();
                    String responseBody = response.body().string();
                    System.err.println(responseBody);

                    if (response.isSuccessful()) {
                        if (responseBody == null || "".equals(responseBody)) {
                            return  "服务器无响应";
                        } else {
                          return responseBody;
                        }
                    } else {
                       return "服务器请求失败 " + response.code() + " " + response.body().string();
                    }
                } catch (Exception e) {
                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                    return "连接服务器错误 " + e.getMessage();
                }
            }

            @Override
            protected void onPostExecute(String responseString) {
                callback.onSuccess(responseString);
            }
        };

        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

}
